// src/pages/Home/DepartmentManagement/DepartmentTree.jsx
import React, { useState } from 'react';
import { Tree, Button, Input, Popconfirm, message, Space } from 'antd';
import {
  PlusOutlined, EditOutlined, DeleteOutlined
} from '@ant-design/icons';

const DepartmentTree = () => {
  const [departments, setDepartments] = useState([
    {
      id: '1',
      name: '公司总部',
      children: [
        {
          id: '2',
          name: '技术研发中心',
          children: [
            { id: '3', name: '前端开发部' },
            { id: '4', name: '后端开发部' },
          ],
        },
        { id: '5', name: '市场运营部' },
      ],
    },
  ]);

  const [selectedKey, setSelectedKey] = useState(null);
  const [newDepartmentName, setNewDepartmentName] = useState('');

  const addDepartment = () => {
    if (!newDepartmentName.trim()) {
      message.warning('请输入部门名称');
      return;
    }

    const newDept = {
      id: Date.now().toString(),
      name: newDepartmentName,
    };

    if (selectedKey) {
      // 添加到选中节点下
      const addChildRecursive = data =>
        data.map(item => {
          if (item.id === selectedKey) {
            return {
              ...item,
              children: [...(item.children || []), newDept],
            };
          }
          if (item.children) {
            return {
              ...item,
              children: addChildRecursive(item.children),
            };
          }
          return item;
        });

      setDepartments(addChildRecursive(departments));
    } else {
      // 添加到根节点
      setDepartments([...departments, newDept]);
    }

    setNewDepartmentName('');
    message.success('部门添加成功');
  };

  const deleteDepartment = (id) => {
    const removeRecursive = data =>
      data.filter(item => {
        if (item.id === id) return false;
        if (item.children) {
          item.children = removeRecursive(item.children);
        }
        return true;
      });

    setDepartments(removeRecursive(departments));
    message.success('部门删除成功');
  };

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
        <Input
          placeholder="输入部门名称"
          value={newDepartmentName}
          onChange={e => setNewDepartmentName(e.target.value)}
          style={{ width: 200 }}
        />
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={addDepartment}
        >
          添加部门
        </Button>
      </div>

      <Tree
        showLine
        treeData={departments}
        fieldNames={{ title: 'name', key: 'id', children: 'children' }}
        titleRender={nodeData => (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>{nodeData.name}</span>
            <Space>
              <Button
                type="text"
                icon={<EditOutlined />}
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  message.info('编辑功能待实现');
                }}
              />
              <Popconfirm
                title="确定删除该部门吗？"
                onConfirm={(e) => {
                  e.stopPropagation();
                  deleteDepartment(nodeData.id);
                }}
              >
                <Button
                  type="text"
                  icon={<DeleteOutlined />}
                  size="small"
                  onClick={e => e.stopPropagation()}
                  danger
                />
              </Popconfirm>
            </Space>
          </div>
        )}
        onSelect={(keys) => setSelectedKey(keys[0])}
        style={{ minHeight: 400 }}
      />
    </div>
  );
};

export default DepartmentTree;
